package com.linewow.xhyy.nihaonew.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.linewow.xhyy.hrxb.Constant;
import com.linewow.xhyy.hrxb.DemoHelper;
import com.linewow.xhyy.hrxb.activity.ChatActivity;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.adapter.TopicDetailAdapter;
import com.linewow.xhyy.nihaonew.application.NiHaoApp;
import com.linewow.xhyy.nihaonew.base.BaseFragment;
import com.linewow.xhyy.nihaonew.base.BaseInfo;
import com.linewow.xhyy.nihaonew.db.NiHaoHelper;
import com.linewow.xhyy.nihaonew.entity.NiHaoEntity;
import com.linewow.xhyy.nihaonew.entity.image.ImagesInfo;
import com.linewow.xhyy.nihaonew.entity.tag.CustomTagsInfo;
import com.linewow.xhyy.nihaonew.entity.topic.TopicDetailInfo;
import com.linewow.xhyy.nihaonew.entity.user.Uinfo;
import com.linewow.xhyy.nihaonew.event.MessageEvent;
import com.linewow.xhyy.nihaonew.helper.GlideImageLoader;
import com.linewow.xhyy.nihaonew.inter.menu.PlusInter;
import com.linewow.xhyy.nihaonew.inter.menu.SendInter;
import com.linewow.xhyy.nihaonew.model.HttpModel;
import com.linewow.xhyy.nihaonew.other.decoration.TopicDetailDecoration;
import com.linewow.xhyy.nihaonew.util.CommonUtil;
import com.linewow.xhyy.nihaonew.util.NewsCallback;
import com.linewow.xhyy.nihaonew.view.input.ImgAdapter;
import com.linewow.xhyy.nihaonew.view.input.TopicInputMenu;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by LXR on 2016/9/6.
 */
public class TopicDetailFragment extends BaseFragment implements PlusInter {
    @Bind(R.id.topic_detail_fragment_recycler)
    RecyclerView topicDetailFragmentRecycler;
    @Bind(R.id.topic_detail_fragment_input)
    TopicInputMenu topicDetailFragmentInput;
    @Bind(R.id.topic_detail_fragment_mask)
    RelativeLayout topicDetailFragmentMask;
    @Bind(R.id.topic_detail_fragment_recycler_rela)
    RelativeLayout topicDetailFragmentRecyclerRela;
    private String TAG = "TopicDetailFragment";
    private String key = "msg";
    private String tid;
    private Type topicDetailInfoType;
    private Gson gson;
    private TopicDetailAdapter adaper;
    private View imgView;
    private RecyclerView recyclerView;
    private List<String> paths;
    private List<TopicDetailInfo<ImagesInfo, Uinfo, CustomTagsInfo>> topicDetailInfos;
    private boolean soundPathFlag = true;
    private ImgAdapter imgAdapter;
    private String soundPath;
    private ArrayList<ImageItem> images;
    public boolean selfFlag;

    @Override
    public View initView() {
        View view = View.inflate(getActivity(), R.layout.fragment_topic_detail, null);
        ButterKnife.bind(this, view);
        initRecyclerView();

        topicDetailFragmentInput.prepareView("name");
        topicDetailFragmentInput.setSendInter(new SendInter() {
            @Override
            public void sendMsg(String string) {
                Log.e(TAG, "收到的信息3:" + string + ">>>" + "是否有录音" + soundPathFlag + ">>>" + "需要上传的图片" + paths.size());
//                Log.e(TAG,"回复的人"+topicDetailFragmentInput.getTopicDetailInfo().uinfo.nickname);
                if (NiHaoApp.flag) {
                    if (string.trim().equals("")) {
                        showToast(getString(R.string.message_no_message));
                    } else {
                        replayInfo(string, soundPathFlag, soundPath, paths);
                    }
                } else {
                    DemoHelper.getInstance().onConnectionConflict();
                }
            }

            @Override
            public void pathMsg(boolean flag) {
                soundPathFlag = flag;
                Log.e(TAG, "是否可用" + flag);
            }

            @Override
            public void pathContent(String path) {
                Log.e(TAG, "地址" + path);
                soundPath = path;
            }
        });
        initInputView();
        initInputList();

        topicDetailFragmentMask.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.e(TAG,"失效？");
                hideSoftKeyboard();
                topicDetailFragmentInput.showContainer(0);
                return false;
            }
        });




        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        hideSoftKeyboard();
    }

    private void replayInfo(String string, boolean soundPathFlag, String soundPath, final List<String> paths) {
        Log.e(TAG, "开始请求了");
        showLoading();
        Map<String, String> map = new HashMap<String, String>();

        map.put("contents", string);
        PostFormBuilder builder = OkHttpUtils.post();
        for (int i = 0; i < paths.size(); i++) {
            builder.addFile("pic[]", new File(paths.get(i)).getName(), new File(paths.get(i)));
        }
        if (soundPath != null) {//先判断是否为空  再判断是否可用
            if (soundPathFlag) {
                map.put("audiotime", "" + CommonUtil.getLength(soundPath));
                builder.addFile("audio", new File(soundPath).getName(), new File(soundPath));
            }
        }

        if (topicDetailFragmentInput.getTopicDetailInfo() == null) {
            map.put("post_type", "reply1");
            builder.url(HttpModel.TOPICREPLY + tid + "&token=" + NiHaoApp.token);
        } else {

            TopicDetailInfo<ImagesInfo, Uinfo, CustomTagsInfo> topicDetailInfo = topicDetailFragmentInput.getTopicDetailInfo();
            map.put("post_type", "replyx2");
            builder.url(HttpModel.TOPICREPLY + tid + "&token=" + NiHaoApp.token + "&rid=" + topicDetailInfo.rid);
        }

        builder
                .params(map)
                .build()
                .execute(new NewsCallback<NiHaoEntity>(NiHaoEntity.class) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        dismissLoading();
                        Log.e(TAG, "错误信息" + e.getMessage());
                    }

                    @Override
                    public void onResponse(NiHaoEntity response, int id) {
                        dismissLoading();
                        topicDetailFragmentInput.resetView();
                        resetImageRecycler();
                        requestInfo();
                        String rid = topicDetailInfos.get(0).rid;
                        String uid = topicDetailInfos.get(0).uid;
                        NiHaoHelper.getInstance().requestReply(uid, rid);
                        Log.e(TAG, "返回了" + response);
                        if (response.status) {
                            showSnack(getString(R.string.reply_success));
                        }
                    }
                });
    }

    @Override
    protected void setUpView() {
        super.setUpView();
        hideSoftKeyboard();
    }

    private void initInputList() {
        paths = new ArrayList<String>();
        imgAdapter = new ImgAdapter(paths, TopicDetailFragment.this.getActivity(), TopicDetailFragment.this);
        LinearLayoutManager manager = new LinearLayoutManager(TopicDetailFragment.this.getActivity());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(imgAdapter);
    }

    public void resetImageRecycler() {
        paths.clear();
        imgAdapter.notifyDataSetChanged();
    }

    private void initInputView() {
        imgView = View.inflate(TopicDetailFragment.this.getActivity(), R.layout.view_add_image, null);
        recyclerView = (RecyclerView) imgView.findViewById(R.id.view_addimg_recycler);
        topicDetailFragmentInput.setImgView(imgView);
    }

    private void initRecyclerView() {
        LinearLayoutManager manager = new LinearLayoutManager(TopicDetailFragment.this.getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        topicDetailFragmentRecycler.setLayoutManager(manager);
        topicDetailFragmentRecycler.setItemAnimator(new DefaultItemAnimator());
        int space = getResources().getDimensionPixelSize(R.dimen.margin_icon_normal);
        topicDetailFragmentRecycler.addItemDecoration(new TopicDetailDecoration(space));
    }

    @Override
    public void initList() {
        super.initList();
    }

    @Override
    public void initData() {
        super.initData();
        EventBus.getDefault().register(TopicDetailFragment.this);
        Bundle bundle = getArguments();
        tid = (String) bundle.get(key);
        topicDetailInfoType = new TypeToken<BaseInfo<TopicDetailInfo<ImagesInfo, Uinfo, CustomTagsInfo>>>() {
        }.getType();
        gson = new Gson();
        Log.e(TAG, "接受到的tid" + tid);
        requestInfo();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(TopicDetailFragment.this);
    }

    private void requestInfo() {
        OkHttpUtils.get().url(HttpModel.TOPICDETAIL + tid + "&token=" + NiHaoApp.token)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, "接受失败了");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        BaseInfo<TopicDetailInfo<ImagesInfo, Uinfo, CustomTagsInfo>> baseInfo = gson.fromJson(response, topicDetailInfoType);
                        if (adaper == null) {
                            topicDetailInfos = baseInfo.data;
                            adaper = new TopicDetailAdapter(TopicDetailFragment.this.getActivity(), topicDetailInfos);
                            topicDetailFragmentRecycler.setAdapter(adaper);
                            try {
                                if (topicDetailInfos.get(0).uinfo.uid.equals(NiHaoApp.uid)) {
                                    selfFlag = true;
                                }
                            } catch (Exception e) {

                            }

                        } else {
                            topicDetailInfos.clear();
                            topicDetailInfos.addAll(baseInfo.data);
                            adaper.notifyDataSetChanged();

                        }
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @Override
    public void plus() {

        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());
        imagePicker.setMultiMode(true);   //多选true
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);
        imagePicker.setSelectLimit(9);
        Intent pickerIntent = new Intent(TopicDetailFragment.this.getActivity(), ImageGridActivity.class);
        startActivityForResult(pickerIntent, 4);
    }

    @Override
    public void onItemClick(int index) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 4) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                Observable.just(images)
                        .map(new Func1<List<ImageItem>, List<String>>() {
                            @Override
                            public List<String> call(List<ImageItem> imageItems) {
                                return imageItemToNewTopicImageInfo(imageItems);
                            }
                        })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<List<String>>() {
                            @Override
                            public void call(List<String> list) {
                                int size1 = paths.size();
                                int size2 = list.size();
                                paths.addAll(list);
                                imgAdapter.notifyItemRangeInserted(size1, size2);
                                recyclerView.scrollToPosition(paths.size());
                            }
                        });
            } else {
                Toast.makeText(TopicDetailFragment.this.getActivity(), "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private List<String> imageItemToNewTopicImageInfo(List<ImageItem> imageItems) {
        List<String> pathList = new ArrayList<String>();
        for (ImageItem temp : imageItems) {
            pathList.add(temp.path);
        }
        return pathList;
    }


    @Subscriber(tag = "Topic", mode = ThreadMode.POST)
    public void updataFragment(MessageEvent messageEvent) {
        Log.e(TAG, "设置完成了" + messageEvent.getIndex());
        TopicDetailInfo<ImagesInfo, Uinfo, CustomTagsInfo> topicDetailInfo = topicDetailInfos.get(messageEvent.getIndex());
        if (!NiHaoApp.uid.equals(topicDetailInfo.uid)) {
            topicDetailFragmentInput.setTopicDetailInfo(topicDetailInfo);
        }
    }

    @Subscriber(tag = "topic", mode = ThreadMode.POST)
    public void topicMessage(MessageEvent messageEvent) {
        Log.e(TAG, "回复话题");
        topicDetailFragmentInput.resetHost();
    }


    @Subscriber(tag = "conversation", mode = ThreadMode.POST)
    public void conversationMessage(MessageEvent messageEvent) {
        Log.e(TAG, "点开回话");
        if (noLogin()) {
            return;
        }
        Intent intent = new Intent(getActivity(), ChatActivity.class);
        intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_SINGLE);
        intent.putExtra(Constant.EXTRA_USER_ID, topicDetailInfos.get(0).uid);
        startActivity(intent);
    }

    @Subscriber(tag = "TopicDetailActivity", mode = ThreadMode.POST)
    public void activityMessage(MessageEvent messageEvent) {
        Log.e(TAG, "回复话题");
        topicDetailFragmentInput.resetHost();
    }

    public boolean getEditFlag() {
        int[] arr = new int[2];
        topicDetailFragmentInput.getLocationOnScreen(arr);
        int inputMinY = CommonUtil.getWindowHei(
                TopicDetailFragment.this.getActivity()) - CommonUtil.dp2px(TopicDetailFragment.this.getActivity(), 60);
        Log.e(TAG, arr[1] + "----" + inputMinY);
        if (arr[1] < inputMinY) {
            Log.e(TAG,"键盘bottom应该收起了");
            return true;
        }
        return false;
    }
}